import pymysql


class DBUtils:
    def __init__(self, host, port, user, password, database):
        self.__host = host
        self.__port = port
        self.__user = user
        self.__password = password
        self.__database = database

    def __get_cur(self):
        self.__db = pymysql.connect(host=self.__host, port=self.__port, user=self.__user, password=self.__password,
                                    database=self.__database, charset='utf8')
        self.__cur = self.__db.cursor()
        return self.__cur

    def execute(self, sql, *args):
        self.__get_cur()
        try:
            execute_result = self.__cur.execute(sql, *args)
            self.__db.commit()
        except Exception as e:
            self.__db.rollback()
            print(e)
            raise e
        self.close()
        return execute_result

    def fetch_one(self, sql, *args):
        self.__get_cur()
        self.__cur.execute(sql, *args)
        result_one = self.__cur.fetchone()
        self.close()
        return result_one

    def close(self):
        self.__cur.close()
        self.__db.close()

